<script>
/**
 * @desc 社区里的用户动态轮播
 */

import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('Community')

export default {
  name: 'article-swiper',
  computed: {
    ...mapState(['posts', 'hasNext'])
  },

  methods: {
    ...mapActions(['getPosts', 'getMorePosts']),
    handleImg(url) {
      wx.previewImage({ urls: [url] })
    },

    handleChange(e) {
      if (e.mp && e.mp.detail) {
        const index = e.mp.detail.current
        if (index === this.posts.length - 1 && this.hasNext) {
          wx.showLoading({ title: '加载中...', mask: true })
          this.getMorePosts()
            .then(() => {
              wx.hideLoading()
            })
            .catch(() => {
              wx.hideLoading()
            })
        }
      }
    }
  },

  mounted() {
    this.getPosts()
  }
}
</script>

<template>
  <div class="article-swiper">
    <swiper class="swiper-container" @animationfinish="handleChange">
      <block v-for="v in posts" :key="v.id">
        <swiper-item class="item">
          <div class="content-container">
            <img
              :src="v.img"
              class="image"
              mode="aspectFill"
              @click="()=>handleImg(v.img)"
            />
            <h2 class="title-bar">
              <span class="name">{{v.author}}</span>
              <span class="date">{{v.date}}</span>
            </h2>
            <p class="article">{{v.text}}</p>
          </div>
        </swiper-item>
      </block>
    </swiper>
  </div>
</template>

<style lang="scss">
$img-size: 560rpx;

.article-swiper {
  flex: 1;
}
.swiper-container {
  height: 100%;
}

.item {
  display: flex;
  flex-direction: column;
  overflow-y: scroll;
}

.content-container {
  margin: 10px;
  border-radius: 10px;
  box-shadow: 0 0 5px #ccc;
  background-color: #fff;
  overflow: hidden;
}

.image {
  flex-shrink: 0;
  width: 100%;
  height: $img-size;
  background-color: $main-background-color;
}

.title-bar {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin: 10px;
  .name {
    font-weight: bold;
  }
  .date {
    font-size: 14px;
    color: $gray-font-color;
  }
}

.article {
  min-height: 7.5em;
  margin: 0 10px 10px;
  overflow-y: scroll;
  font-size: 16px;
  line-height: 1.5;
}
</style>
